<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="LeetCode,">










<meta name="description" content="贪心思想的原理：保证每次操作都是局部最优，并且最后的结果是全局最优的。 分配饼干 LeetCode 455 Input: [1,2], [1,2,3]Output: 2 题目描述：每个孩子都有一个满足度，每个饼干都有一个大小，只有饼干的大小大于等于孩子的满足度才能满足孩子。每个孩子只能分配一块饼干。  给每个孩子的饼干应该尽可能小，但是又能满足他。这样满足度大的饼干就能满足满足度比较大的孩子。就可">
<meta name="keywords" content="LeetCode">
<meta property="og:type" content="article">
<meta property="og:title" content="贪心思想">
<meta property="og:url" content="https://xiver.gitee.io/2019/06/30/贪心思想/index.html">
<meta property="og:site_name" content="Condi">
<meta property="og:description" content="贪心思想的原理：保证每次操作都是局部最优，并且最后的结果是全局最优的。 分配饼干 LeetCode 455 Input: [1,2], [1,2,3]Output: 2 题目描述：每个孩子都有一个满足度，每个饼干都有一个大小，只有饼干的大小大于等于孩子的满足度才能满足孩子。每个孩子只能分配一块饼干。  给每个孩子的饼干应该尽可能小，但是又能满足他。这样满足度大的饼干就能满足满足度比较大的孩子。就可">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-06-30T07:56:50.893Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="贪心思想">
<meta name="twitter:description" content="贪心思想的原理：保证每次操作都是局部最优，并且最后的结果是全局最优的。 分配饼干 LeetCode 455 Input: [1,2], [1,2,3]Output: 2 题目描述：每个孩子都有一个满足度，每个饼干都有一个大小，只有饼干的大小大于等于孩子的满足度才能满足孩子。每个孩子只能分配一块饼干。  给每个孩子的饼干应该尽可能小，但是又能满足他。这样满足度大的饼干就能满足满足度比较大的孩子。就可">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://xiver.gitee.io/2019/06/30/贪心思想/">





  <title>贪心思想 | Condi</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Condi</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://xiver.gitee.io/2019/06/30/贪心思想/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Condi">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Condi">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">贪心思想</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-06-30T08:41:10+08:00">
                2019-06-30
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>贪心思想的原理：保证每次操作都是局部最优，并且最后的结果是全局最优的。</p>
<h1 id="分配饼干"><a href="#分配饼干" class="headerlink" title="分配饼干"></a>分配饼干</h1><blockquote>
<p>LeetCode 455</p>
<p>Input: [1,2], [1,2,3]<br>Output: 2</p>
<p>题目描述：每个孩子都有一个满足度，每个饼干都有一个大小，只有饼干的大小大于等于孩子的满足度才能满足孩子。每个孩子只能分配一块饼干。</p>
</blockquote>
<p>给每个孩子的饼干应该尽可能小，但是又能满足他。这样满足度大的饼干就能满足满足度比较大的孩子。就可以保证满足最多的孩子。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> findContentChildren = <span class="function"><span class="keyword">function</span> (<span class="params">g, s</span>) </span>&#123;</span><br><span class="line">  g.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a - b)</span><br><span class="line">  s.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a - b)</span><br><span class="line">  <span class="keyword">let</span> gi = <span class="number">0</span>, si = <span class="number">0</span></span><br><span class="line">  <span class="keyword">while</span> (gi &lt; g.length &amp;&amp; si &lt; s.length) &#123;</span><br><span class="line">    <span class="keyword">if</span> (s[si] &gt;= g[gi]) &#123;</span><br><span class="line">      gi++</span><br><span class="line">    &#125;</span><br><span class="line">    si++</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> gi</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="不重叠的区间个数"><a href="#不重叠的区间个数" class="headerlink" title="不重叠的区间个数"></a>不重叠的区间个数</h1><blockquote>
<p>LeetCode 435</p>
<p>Input: [ [1,2], [1,2], [1,2] ]<br>Output: 2</p>
<p>题目描述：计算一组区间要做到不重叠，需要移除的区间个数。要做到移除的区间个数最小，即要计算最多能组成的不重叠区间数。然后用总区间减去不重叠的区间数。</p>
</blockquote>
<p>每次选择，区间结尾如果小于等于区间开头，则不重叠。区间的结尾越小，留给后面的区间的空间越大，可以选择的区间个数也越大。</p>
<p>所以对区间的结尾进行排序，每次选择结尾最小，并且和前一个不重叠的区间。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> eraseOverlapIntervals = <span class="function"><span class="keyword">function</span> (<span class="params">intervals</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (intervals.length === <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line">  intervals.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a[<span class="number">1</span>] - b[<span class="number">1</span>])</span><br><span class="line">  <span class="keyword">let</span> res = <span class="number">1</span>, end = intervals[<span class="number">0</span>][<span class="number">1</span>]</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; intervals.length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (end &gt; intervals[i][<span class="number">0</span>]) <span class="keyword">continue</span></span><br><span class="line">    end = intervals[i][<span class="number">1</span>]</span><br><span class="line">    res++</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> intervals.length - res</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>一定要考虑边界值。当传入空数组时，返回0。</p>
<h1 id="投飞镖刺破气球"><a href="#投飞镖刺破气球" class="headerlink" title="投飞镖刺破气球"></a>投飞镖刺破气球</h1><blockquote>
<p>LeetCode 452</p>
<p>Input:<br>[[10,16], [2,8], [1,6], [7,12]]<br>Output:<br>2</p>
<p>题目描述：气球在一个水平数轴上摆放，可以重叠，飞镖垂直坐标轴投向，使得路径上的气球都被刺破。求解最小的投飞镖次数使得所有气球都被刺破。</p>
</blockquote>
<p>计算不重叠的区间个数，区别是边界也是重叠区间。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> findMinArrowShots = <span class="function"><span class="keyword">function</span> (<span class="params">points</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (points.length === <span class="number">0</span>) <span class="keyword">return</span> <span class="number">0</span></span><br><span class="line">  points.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a[<span class="number">1</span>] - b[<span class="number">1</span>])</span><br><span class="line">  <span class="keyword">let</span> res = <span class="number">1</span>, end = points[<span class="number">0</span>][<span class="number">1</span>]</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; points.length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (end &gt;= points[i][<span class="number">0</span>]) <span class="keyword">continue</span></span><br><span class="line">    res++</span><br><span class="line">    end = points[i][<span class="number">1</span>]</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="根据身高和序号重组队列"><a href="#根据身高和序号重组队列" class="headerlink" title="根据身高和序号重组队列"></a>根据身高和序号重组队列</h1><blockquote>
<p>LeetCode 406</p>
<p>Input:<br>[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]<br>Output:<br>[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]</p>
<p>题目描述：每个学生用两个分量表示（h,k）,h表示身高，k表示前面有&gt;=k个学生的身高和他一样高。</p>
<p>因为包保证前面有k个学生的身高大于等于他本身。所以先h降序排列，k升序排列。每个学生都插入到底k个位置，保证前面有k个学生身高大于等于他。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> reconstructQueue = <span class="function"><span class="keyword">function</span> (<span class="params">people</span>) </span>&#123;</span><br><span class="line">  people.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> a[<span class="number">0</span>] === b[<span class="number">0</span>] ? a[<span class="number">1</span>] - b[<span class="number">1</span>] : b[<span class="number">0</span>] - a[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="built_in">console</span>.log(people)</span><br><span class="line">  <span class="keyword">let</span> res = []</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i <span class="keyword">of</span> people) &#123;</span><br><span class="line">    res.splice(i[<span class="number">1</span>], <span class="number">0</span>, i)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="买卖股票最大的收益-I"><a href="#买卖股票最大的收益-I" class="headerlink" title="买卖股票最大的收益 I"></a>买卖股票最大的收益 I</h1><blockquote>
<p>LeetCode 121</p>
<p>题目描述：只进行一次股票交易，买入卖出求最大利益。</p>
</blockquote>
<p>记录前面的最小价格，然后将整个最小价格作为买入价格。将当前价格作为售出价格，查看当前收益是不是最大收益。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> maxProfit = <span class="function"><span class="keyword">function</span> (<span class="params">prices</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> minPrice = prices[<span class="number">0</span>]</span><br><span class="line">  <span class="keyword">let</span> res = <span class="number">0</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; prices.length; i++) &#123;</span><br><span class="line">    <span class="keyword">let</span> rase = <span class="number">0</span></span><br><span class="line">    <span class="keyword">if</span> (prices[i] &lt; minPrice) minPrice = prices[i]</span><br><span class="line">    <span class="keyword">if</span> (prices[i] &gt; minPrice) rase = prices[i] - minPrice</span><br><span class="line">    <span class="keyword">if</span> (rase &gt; res) res = rase</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="买卖股票的最大收益-II"><a href="#买卖股票的最大收益-II" class="headerlink" title="买卖股票的最大收益 II"></a>买卖股票的最大收益 II</h1><blockquote>
<p>LeetCode 122</p>
<p>题目描述：可以进行多次交易，但是交易不能交叉。即买入股票，卖了之后才买再买。求最大利益</p>
</blockquote>
<p>只要当前的金额大于前一项的金额，即可看做获得收益。即每次到当前金额时保证之前的利润都是最大的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> maxProfit = <span class="function"><span class="keyword">function</span> (<span class="params">prices</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> res = <span class="number">0</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; prices.length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (prices[i] &gt; prices[i - <span class="number">1</span>]) res += prices[i] - prices[i - <span class="number">1</span>]</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="种植花朵"><a href="#种植花朵" class="headerlink" title="种植花朵"></a>种植花朵</h1><blockquote>
<p>LeetCode 605</p>
<p>Input: flowerbed = [1,0,0,0,1], n = 1<br>Output: True</p>
<p>题目描述：1 表示种植了花朵，0 表示没有种植花朵。花朵之间至少间隔一个单位的间隙。求解是否能种下 n 朵花</p>
</blockquote>
<p>需要考虑边界，在第一个和最后个位置时考虑左边和右边可以看做 0 ，没有种植花朵。其他位置时，看左右是否种植花朵，如果都为0，则当前位置可以设置1，然后计数器+1，最后看计数器的大小是否大于等于n。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> canPlaceFlowers = <span class="function"><span class="keyword">function</span> (<span class="params">flowerbed, n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> res = <span class="number">0</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; flowerbed.length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (flowerbed[i] === <span class="number">1</span>) <span class="keyword">continue</span></span><br><span class="line">    <span class="keyword">let</span> pre = i === <span class="number">0</span> ? <span class="number">0</span> : flowerbed[i - <span class="number">1</span>]</span><br><span class="line">    <span class="keyword">let</span> next = i === flowerbed.length - <span class="number">1</span> ? <span class="number">0</span> : flowerbed[i + <span class="number">1</span>]</span><br><span class="line">    <span class="keyword">if</span> (pre === <span class="number">0</span> &amp;&amp; next === <span class="number">0</span>) &#123;</span><br><span class="line">      flowerbed[i] = <span class="number">1</span></span><br><span class="line">      res++</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(flowerbed)</span><br><span class="line">  <span class="keyword">return</span> res &gt;= n</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="判断是否为子序列"><a href="#判断是否为子序列" class="headerlink" title="判断是否为子序列"></a>判断是否为子序列</h1><blockquote>
<p>LeetCode 392</p>
<p>s = “abc”, t = “ahbgdc”<br>Return true.</p>
</blockquote>
<p>遍历需要判断子序列的序列，对于子序列的每一个字符，在对照序列中依次从左至右遍历，如果找到了，子序列指向下一位，然后对照序列接着遍历，重复此步骤。如果对照序列遍历完成后，子序列也遍历完成了，说明是子序列，否则不是。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> isSubsequence = <span class="function"><span class="keyword">function</span> (<span class="params">s, t</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> s0 = <span class="number">0</span>, t0 = <span class="number">0</span></span><br><span class="line">  <span class="keyword">while</span> (t0 &lt; t.length) &#123;</span><br><span class="line">    <span class="keyword">if</span> (s[s0] === t[t0]) &#123;</span><br><span class="line">      s0++</span><br><span class="line">    &#125;</span><br><span class="line">    t0++</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> s0 === s.length</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="修改一个数变成非递减数组"><a href="#修改一个数变成非递减数组" class="headerlink" title="修改一个数变成非递减数组"></a>修改一个数变成非递减数组</h1><blockquote>
<p>LeetCode 665</p>
<p>Input: [4,2,3]<br>Output: True</p>
<p>题目描述：判断一个数组能否只修改一个数，使之变成非递减数组。</p>
</blockquote>
<p>当 nums[i] &lt; nums[i-1] 时，需要思考，修改哪一个数。理论上两个都可以修改。nums[i] = nums[i-1] or nums[i-1]  = nums[i] 都可以。如果修改当前数的话，会使之变大，影响后序的判断。所以一般情况修改前一个数。</p>
<p><strong>特殊情况：</strong>当前的数比 nums[i-2] 还要小，由于之前的数已经排序好了，此时再改变 nums[i-1] 会使得 nums[i-1] 变小，所以此时 nums[i] = nums[i-1]</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> checkPossibility = <span class="function"><span class="keyword">function</span> (<span class="params">nums</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> res = <span class="number">0</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; nums.length &amp;&amp; res &lt; <span class="number">2</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (nums[i] &gt;= nums[i - <span class="number">1</span>]) <span class="keyword">continue</span></span><br><span class="line">    res++</span><br><span class="line">    <span class="keyword">if</span> (i &gt;= <span class="number">2</span> &amp;&amp; nums[i] &lt; nums[i - <span class="number">2</span>]) nums[i] = nums[i - <span class="number">1</span>]</span><br><span class="line">    <span class="keyword">else</span> nums[i - <span class="number">1</span>] = nums[i]</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res &lt;= <span class="number">1</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="子数组最大的和"><a href="#子数组最大的和" class="headerlink" title="子数组最大的和"></a>子数组最大的和</h1><blockquote>
<p>LeetCode 53</p>
<p>For example, given the array [-2,1,-3,4,-1,2,1,-5,4],<br>the contiguous subarray [4,-1,2,1] has the largest sum = 6.</p>
</blockquote>
<p>当遍历到当前数时，保证之前的最大和是最大的。</p>
<p>要保证连续数组的最大和，所以负数连续肯定会使最后的值变小。</p>
<p>所以当之前的连续和为负数时，当遇到当前值时，丢弃掉之前的和，从当前值开始计算。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> maxSubArray = <span class="function"><span class="keyword">function</span> (<span class="params">nums</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> preSum = nums[<span class="number">0</span>], maxSum = preSum</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">1</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">    preSum = preSum &gt; <span class="number">0</span> ? preSum + nums[i] : nums[i]</span><br><span class="line">    maxSum = <span class="built_in">Math</span>.max(maxSum, preSum)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> maxSum</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h1 id="分隔字符串使同种字符出现在一起"><a href="#分隔字符串使同种字符出现在一起" class="headerlink" title="分隔字符串使同种字符出现在一起"></a>分隔字符串使同种字符出现在一起</h1><blockquote>
<p>LeetCode 763</p>
<p>Input: S = “ababcbacadefegdehijhklij”<br>Output: [9,7,8]</p>
<p>题目要求：要求分割的数组大小最大。</p>
</blockquote>
<p>从左至右遍历字符串，对于每个字符，找到它最后出现的位置。然后对这个区间进行遍历，看它最后出现的位置是否大于之前的字符最后出现的位置，如果大于则扩展这个区间。遍历完成后，同一个字母都值出现在这个区间内。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> partitionLabels = <span class="function"><span class="keyword">function</span> (<span class="params">S</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> res = []</span><br><span class="line">  <span class="keyword">let</span> firstIndex = <span class="number">0</span></span><br><span class="line">  <span class="keyword">while</span> (firstIndex &lt; S.length) &#123;</span><br><span class="line">    <span class="keyword">let</span> lastIndex = firstIndex</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = firstIndex; i &lt; S.length &amp;&amp; i &lt;= lastIndex; i++) &#123;</span><br><span class="line">      <span class="keyword">let</span> index = S.lastIndexOf(S[i])</span><br><span class="line">      <span class="keyword">if</span> (index &gt; lastIndex) &#123;</span><br><span class="line">        lastIndex = index</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    res.push(lastIndex - firstIndex + <span class="number">1</span>)</span><br><span class="line">    firstIndex = lastIndex + <span class="number">1</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> res</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/LeetCode/" rel="tag"># LeetCode</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/06/29/排序/" rel="next" title="排序">
                <i class="fa fa-chevron-left"></i> 排序
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/06/30/二分查找/" rel="prev" title="二分查找">
                二分查找 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Condi</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#分配饼干"><span class="nav-number">1.</span> <span class="nav-text">分配饼干</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#不重叠的区间个数"><span class="nav-number">2.</span> <span class="nav-text">不重叠的区间个数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#投飞镖刺破气球"><span class="nav-number">3.</span> <span class="nav-text">投飞镖刺破气球</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#根据身高和序号重组队列"><span class="nav-number">4.</span> <span class="nav-text">根据身高和序号重组队列</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#买卖股票最大的收益-I"><span class="nav-number">5.</span> <span class="nav-text">买卖股票最大的收益 I</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#买卖股票的最大收益-II"><span class="nav-number">6.</span> <span class="nav-text">买卖股票的最大收益 II</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#种植花朵"><span class="nav-number">7.</span> <span class="nav-text">种植花朵</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#判断是否为子序列"><span class="nav-number">8.</span> <span class="nav-text">判断是否为子序列</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#修改一个数变成非递减数组"><span class="nav-number">9.</span> <span class="nav-text">修改一个数变成非递减数组</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#子数组最大的和"><span class="nav-number">10.</span> <span class="nav-text">子数组最大的和</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分隔字符串使同种字符出现在一起"><span class="nav-number">11.</span> <span class="nav-text">分隔字符串使同种字符出现在一起</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Condi</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
